package com.example.mqtt.service;

import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromAddress;


    @Value("${alert.email}")
    private String toAddress;

//    @Async
//    public void sendAlertEmail(BigDecimal value) {
//        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom(fromAddress);
//        message.setTo(toAddress);
//        message.setSubject("Threshold Alert!");
//        message.setText(String.format("Value %.2f exceeds 0.9 threshold!", value));
//        mailSender.send(message);
//    }
    @Async
    public void sendAlertEmail(BigDecimal value) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 严格符合RFC标准的发件人格式
            helper.setFrom(new InternetAddress(fromAddress, "系统监控", "UTF-8"));
            helper.setTo(toAddress);
            helper.setSubject("阈值告警通知");
            helper.setText(String.format("当前值: %.2f 超过阈值0.9", value));

            mailSender.send(message);
        } catch (Exception ex) {
            // 添加重试或报警逻辑
            System.err.println("邮件发送失败: " + ex.getMessage());
            // 可在此添加重试机制
        }
    }
}
